package com.icehand.payment.pay.wechat.app;

import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.icehand.common.constants.CommonConstants;
import com.icehand.common.enums.PayChannelEnum;
import com.icehand.mybatis.payment.mapper.PayNotifyRecordMapper;
import com.icehand.payment.model.PayWrapper;
import com.icehand.payment.pay.wechat.*;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.web.client.RestTemplate;

/**
 * 微信APP支付
 * @author icehand
 */
@Slf4j
public class WechatAppPay extends BaseWechatPay {
    private static final PayChannelEnum CHANNEL = PayChannelEnum.WECHAT_APP_PAY;

    public WechatAppPay(RestTemplate restTemplate, XmlMapper xmlMapper,
                        PayNotifyRecordMapper payNotifyRecordMapper) {
        super(restTemplate, xmlMapper, payNotifyRecordMapper);
    }

    @Override
    protected boolean isWechatPay(PayChannelEnum payChannelEnum) {
        return CHANNEL.equals(payChannelEnum);
    }

    @Override
    protected WeChatPaymentUnifiedOrderRequest createUnifiedOrder(PayWrapper payWrapper) {
        return super.createUnifiedOrder(payWrapper);
    }

    @Override
    protected void doAfter(PayWrapper payWrapper, WeChatPaymentUnifiedOrderResponse response) {
        if(payWrapper.getBizResult().isSuccess()){
            WeChatAppPayment weChatAppPayment = new WeChatAppPayment()
                    .setAppId(response.getAppId())
                    .setNonceStr(WeChatPaymentSignatureUtils.generateNonceStr())
                    .setPartnerId(response.getMchId())
                    .setTimestamp(new DateTime().getMillis()/1000 + "")
                    .setPrepayId(response.getPrepayId());
            weChatAppPayment.createSign(payWrapper.getConfig().getString(CommonConstants.K_SECRET));
            payWrapper.putData(weChatAppPayment);
        }
    }

    @Override
    public PayChannelEnum getChannel() {
        return CHANNEL;
    }
}
